
/**
 * @version $Id$
 * @create 2012-10-21 16:57:09 By xjiujiu
 * @description HongJuZi Framework
 * @copyRight Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */
 (function($) {
	 
     /**
      * HHJsLib扩展工具类 
      * 
      * 收集一些用户的小功能，小工具函数等 
      * 
      * @author xjiujiu <xjiujiu@foxmail.com>
      * @package None
      * @since 1.0.0
      */
     var HHUtils    = {
		
    	/**
	     * 高亮显示当前链接元素[现在还得基于Jquery]
	     * 
	     * <code>
	     * //HTML部分:
	     * <div class="navmenu">
	         * <ul>
	             * <li><a href="link1">link1</a></li>
	             * <li><a href="link2">link2</a></li>
	             * <li><a href="link3">link3</a></li>
	         * </ul>
	     * </div>
	     * //JS部分：
	     *  HHJsLib.highLightElement('.navmenu ul li', 'active', 0);
	     * </code>
	     *
	     * @param string findDom 查找的当前元素
	     * @param string currentClass 当前选中的样式名
	     * @param string level 相对于当前查到元素的层级关系，往下是-N, 往上是+N
	     * @param string callback 对找到的目标附加的函数调用
	     *
	     * @return void
	     */
	     highLightElement: function(findDom, currentClass, level, callback) {
	        var url         = window.location.href;
	        var nowHref     = url.substring(url.indexOf('index'));//拿到当前访问的页面及查询内容
	        if(typeof nowHref == 'undefined' || nowHref == '') {
	            return true;
	        }
	        jQuery(findDom).each(function() {
	            var curHref     = jQuery(this).children('a').attr('href');
	            if(typeof curHref != 'undefined' && (curHref == url || curHref == nowHref)) {
                    var targetDom = curTargetDom = $(this);
                    if(level < 0) {
                        for(var i = 0; i > level; i --) {
                            targetDom    = jQuery(targetDom).children('a'); 
                        }
                    } else if(level > 0) {
                        for(var i = 0; i < level; i ++) {
                            targetDom    = jQuery(targetDom).parent(); 
                        }
                    }
                    if(typeof callback != 'undefined') {
                        callback(targetDom, curTargetDom[0]);
                    }
                    jQuery(targetDom[0]).addClass(currentClass);
                    
                    return false;
                }
	        });
	     },
    		 
         /**
          * 回到页面的面部 
          * 
          * 用法：
          * <code>
          * HHJsLib.goTop('btn-top-id');
          * </code>
          * 
          * @author xjiujiu <xjiujiu@foxmail.com>
          * @access public
          * @param  String btnId 按钮的ID
          * @return void
          * @throws none
          */
        goTop: function(btnId, show, hide) {
            var btn             = document.getElementById(btnId);
            var browserName     = navigator.userAgent.toLowerCase();
            if(/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName)) {
                var d = document.body;
            }else if(/webkit/i.test(browserName) && !this.chrome) {
                var d = document.body;
            }else{
                var d = document.documentElement ? document.documentElement : document.body;
            }
            window.onscroll     = set;
            btn.onclick         = function () {
                btn.className   = hide;
                window.onscroll = null;
                this.timer=setInterval(function() {
                    d.scrollTop -= Math.ceil(d.scrollTop*0.8);
                    if(d.scrollTop==0) clearInterval(btn.timer,window.onscroll=set);
                }, 10);
            };
            function set(){
                btn.className = d.scrollTop >= 100 ? show : hide;
            }
        },
        
        /**
          * 重定向到其它页面 
          * 
          * 用法：
          * <code>
          * HHJsLib.redirect('http://www.xjiujiu.com', target);
          * </code>
          * 
          * @author xjiujiu <xjiujiu@foxmail.com>
          * @access public
          * @param  String url 目标地址
          * @param  String target 重定向的目标位置: self, blank
          * @return void
          * @throws none
          */
        redirect: function(url, target) {
            if(typeof target == 'undefined') {
                target  = 'self';
            }
            switch(target) {
                case 'blank':
                    window.open(url);
                    break;
                case 'self':
                default:
                    window.location.href    = url;
                    break;
            }
        },
       
        /**
          * 重定向到其它页面 
          * 
          * 用法：
          * <code>
          * HHJsLib.maskStatus('td.pass', {"是": "pass-ok", "否": "pass-no"});
          * </code>
          * 
          * @author xjiujiu <xjiujiu@foxmail.com>
          * @access public
          * @param  String dom 需要查找的目标
          * @param  Map<String, String> 值对应的状态样式表,如：{1: "ok-status"}
          * @return void
          */
        maskStatus: function(dom, map) {
        	$(dom).each(function() {
        		var value 	= $.trim($(this).html());
        		if(typeof map[value] != 'undefined') {
        			$(this).addClass(map[value]);
        		}
        	});
        },
        
        /**
          * 打印预览，默认为A4的纸大小
          * 
          * 用法：
          * <code>
          * HHJsLib.printPriview('#print-btn-id', "我是需要打印的内容");
          * </code>
          * 
          * @author xjiujiu <xjiujiu@foxmail.com>
          * @access public
          * @param  String printBtndom 需要绑定的按钮
          * @param  String callback 回调函数 得到需要打印的内容
          * @param  String title 打印页面的标题
          * @return void
          */
        printPriview: function(printBtndom, callback, title) {
        	$(printBtndom).click(function() {
        		var content 	= callback();
        		var htmlTpl 	= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"
								+ "<html xmlns=\"http://www.w3.org/1999/xhtml\">"
								+ "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
		        				+ "<head>"
		        				+ "{link}"
		        				+ "<style text=\"text/css\">"
		        				+ "		.print-btn-line { text-align: right; padding-right: 10px;}"
		        				+ "		.print-page { width: 1000px; margin: 0px auto; padding-bottom: 10px; }"
		        				+ "		.page-title { text-align: center; }"
		        				+ " 	{style}"
		        				+ "</style>"
		        				+ "</head>"
		        				+ "<p class=\"print-btn-line\">"
        						+ "<a href=\"javascript:void(0);\" id=\"start-print-id\">点击确认打印</a></p>"
		        				+ "{title}"
		        				+ "<div class=\"print-page\" id=\"content-id\">{content}</div>"
		        				+ "<script type=\"text/javascript\">"
		        				+ "document.getElementById(\"start-print-id\").onclick = function() {"
		        				+ "this.innerHTML = '';"
		        				+ "window.print();"
		        				+ "this.innerHTML = '点击确认打印'"
		        				+ "}"
		        				+ "</script>"
		        				+ "</html>";
    			newWindow 		= window.open("", "打印预览", "fullscreen");
    			newWindow.title = "打印预览";
    			newWindow.document.open("text/html", "replace");
    			newWindow.moveBy(0, 0);
    			newWindow.resizeTo(window.screen.availWidth, window.screen.availHeight);
        		var links 		= "";
    			$("link").each(function() {
    				links 		+= "<link rel=\"stylesheet\" href=\"" + $(this).attr("href") + "\" type=\"text/css\" />";
    			});
        		var styles 		= "";
    			$("style").each(function() {
    				styles 		+= $(this).html();
    			});
    			
    			htmlTpl 		= htmlTpl.replace(/{link}/, links);
    			htmlTpl 		= htmlTpl.replace(/{style}/, styles);
    			if(typeof title != 'undefined' && "" != title) {
	    			htmlTpl 	= htmlTpl.replace(/{title}/, "<h3 class=\"page-title\">" + title + "</h3>");
    			} else {
	    			htmlTpl 	= htmlTpl.replace(/{title}/, "");
    			}
    			htmlTpl 		= htmlTpl.replace(/{content}/, content);
    			newWindow.document.write(htmlTpl);
    			newWindow.document.close();
    		});
        },
        
        /**
          * 删除Table指定的列
          * 
          * 用法：
          * <code>
          * HHJsLib.deleteTableColumn($("#table-content-area").html(), [0, 12]);
          * </code>
          * 
          * @author xjiujiu <xjiujiu@foxmail.com>
          * @access public
          * @param  String table 需要处理的表格
          * @param  Array subInfo 需要删除的列信息
          * @return String 删除列后的表格HTML代码
          */
        deleteTableColumn: function(table, subInfo) {
        	var $contentHtml 	= $(table);
        	if(typeof subInfo == 'undefined') {
        		return $contentHtml[0].outerHTML;
        	}
			var row 		= -1;
        	$contentHtml.find("tr").each(function() {
        		row ++;
        		var subColumns 	= [];
        		if(typeof subInfo[row] != 'undefined') {
        			subColumns 	= subInfo[row];
        		} else if(typeof subInfo['a'] != 'undefined') {
        			subColumns 	= subInfo['a'];
        		}
	    		for(var i = 0; i < subColumns.length; i ++) {
	    			//减去刚才去掉的那些列们，且它们刚好是i的数量
	        		$(this).find("td:eq(" + (subColumns[i] - i) + ")").remove();
	        	}
        	});
    		
	    	return $contentHtml[0].outerHTML;
        },

        /**
          * 二级下拉效果
          * 
          * 用法：
          * JS CODE:
          * <code>
          * HHJsLib.dropMenu("ul.main-menu li", "dl.sub-link", "selected");
          * </code>
          * HTML CODE:
          * <code>
          * <ul class="main-menu">
          * <li><a href="#">主菜单</a></li>
          * <li>
          *     <a href="#">主菜单</a>
          *     <dl class="sub-link">
          *      <dd><a href="#">子菜单</a></dd>
          *      <dd><a href="#">子菜单</a></dd>
          *      <dd><a href="#">子菜单</a></dd>
          *     </dl>
          * </li>
          * </code>
          * 
          * @author xjiujiu <xjiujiu@foxmail.com>
          * @access public
          * @param  String target 需要处理的对象
          * @param  Array subElementClass 子菜单的样式名 
          * @param  Array currentClass 选中后的样式
          * @return String 删除列后的表格HTML代码
          */
        dropMenu: function (target, subElementClass, currentClass){
            $(target).each(function(){
                var theSpan = $(this);
                var theMenu = theSpan.find(subElementClass);
                var tarHeight = theMenu.height();
                theMenu.css({height:0,opacity:0});
                theSpan.hover(
                    function(){
                        $(this).addClass(currentClass);
                        theMenu.stop().show().animate({height:tarHeight,opacity:1},400);
                    },
                    function(){
                        $(this).removeClass(currentClass);
                        theMenu.stop().animate({height:0,opacity:0},400,function(){
                            $(this).css({display:"none"});
                        });
                    }
                );
            });
        },

        /**
          * 二级下拉效果
          * 
          * 用法：
          * JS CODE:
          * <code>
          * HHJsLib.dropMenu("ul.main-menu li", "dl.sub-link", "selected");
          * </code>
          * HTML CODE:
          * <code>
            <ul class="menu-list">
                <li><a href="###">链接一</a>
                	<ul class="sub-menu-list">
                        <li><a href="#">下级链接一</a></li> 
                        <li><a href="#">下级链接二</a></li> 
                     </ul>
                </li>
            </ul>                
          * </code>
          * 
          * @author xjiujiu <xjiujiu@foxmail.com>
          * @access public
          * @param  String target 需要处理的对象
          * @param  object callback 回调函数
          * @return void
          */
        slideUpDown: function(target, callback) {
			$(target).click(function () {
				$(this).parent().siblings().find("ul").slideUp("normal"); // Slide up all sub menus except the one clicked
				$(this).next().slideToggle("normal"); // Slide down the clicked sub menu
				if(typeof callback != 'undefined') {
					callback($(this));
				}
				return true;
			});
        },

         /**
         * 字段域提示工具 
         * 
         * @desc
         * 
         * @author xjiujiu <xjiujiu@foxmail.com>
         * @access public
         * @param  String target 需要提示的表单域对象，可以是id或是class名或tag
         * @param  String def 提示的信息
         */
        fieldHint: function(target, def) {
            if('undefined' == typeof def) {
                def         = $(target).first().val();
            }
            var $target     = $(target).each(function() {
                var $this   = $(this);
                if("" == $this.val() || def == $this.val()) {
                    $this.val(def);
                    $this.val(def).css('color', '#999');
                }
                $this.click(function() {
                    if(def == $(this).val()) {
                        $(this).val("");
                    }
                    $(this).css('color', '#000')
                }).blur(function() {
                    if('' == $(this).val()) {
                        $(this).val(def);
                        $(this).css('color', '#999');
                    }
                });
            });
        },

        /**
         * 设置成主页 
         * 
         * @desc
         * 
         * @author xjiujiu <xjiujiu@foxmail.com>
         * @access public
         * @param Object obj 当前的DOM对象
         * @param String val 当前的网址
         */
        setHomePage: function (obj, val){
            try{
                obj.style.behavior='url(#default#homepage)';
                obj.setHomePage(val);
            } catch(e){
                if(window.netscape) {
                    try {
                        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
                    } catch (e)  { 
                        alert("此操作被浏览器拒绝！");  
                    }
                    var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService
                    (Components.interfaces.nsIPrefBranch);
                    prefs.setCharPref('browser.startup.homepage',val);
                }
            }
        },
        
        /**
         * 加入到收藏夹 
         * 
         * @desc
         * 
         * @author xjiujiu <xjiujiu@foxmail.com>
         * @access public
         * @param  String URL 需要收藏的链接
         * @param  String title 网页标题
         */
        addFavorite: function (URL, title) {
            try {
                window.external.addFavorite(URL, title);
            } catch (e) {
                try {
                    window.sidebar.addPanel(title, URL, "");
                } catch (e) {
                    alert("加入收藏失败，请使用Ctrl+D进行添加");
                }
            }
        }
     };

     //注册到HHJsLib的扩展中
     HHJsLib.extend(HHUtils);
 })(jQuery);
